package com.leimo.controller;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.leimo.service.WechatPayService;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

/**
 * 微信公众号
 *
 * @author 段誉
 * @create 2019-04-19 13:10
 */
@Slf4j
@Controller
@RequestMapping("wechat")
public class WechatController {
  /**
   * 微信登录作用域
   */
  private static final String WECHAT_LOGIN_SCOPE = "snsapi_login";

  @Autowired
  private WxMpService wxMpService;
  @Autowired
  private WechatPayService wechatPayService;


  /**
   * @desc 微信登录
   * @Author 段誉
   * @Date 2019/4/19 13:29
   * @method
   */
  @GetMapping("to_login")
  public String toLogin(HttpServletRequest request) {
    String state = RandomStringUtils.randomAlphanumeric(32);
    request.getSession().setAttribute("state", state);
    String callBackUrl = request.getRequestURL().toString()
            .replaceAll(request.getRequestURI(), "") + "/wechat/login_call_back";
    return "redirect:" + wxMpService.buildQrConnectUrl(callBackUrl, WECHAT_LOGIN_SCOPE, state);
  }

  /**
   * @desc 登录回调
   * @Author 段誉
   * @Date 2019/4/19 13:29
   * @method
   */
  @GetMapping("login_call_back")
  @ResponseBody
  public String wechatLogin(String code, String state, HttpServletRequest request) {
    String stateSession = (String) request.getSession().getAttribute("state");
    if (!state.equals(stateSession)) {
      throw new RuntimeException("两次state不一致");
    }
    String openId = null;
    try {
      WxMpOAuth2AccessToken token = wxMpService.oauth2getAccessToken(code);
      openId = token.getOpenId();
    } catch (WxErrorException e) {
      log.error("获取微信token异常", e);
      throw new RuntimeException(e);
    }
    return openId;
  }

  /**
   * @desc 发送红包
   * @Author 段誉
   * @Date 2019/4/19 15:03
   * @method
   */
  @PostMapping("/send_redpack")
  @ResponseBody
  public String sendRedpack(String openId) throws WxPayException {

    wechatPayService.sendRedpack(openId);
    return "发送成功！！";
  }


}
